/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlProdServ;
import Controlador.ControlPromocion;
import Controlador.ControlProveedor;
import Modelo.Producto;
import Modelo.Promocion;
import Modelo.Proveedor;
import Modelo.Servicio;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Damian
 */
public class VisualizarPromociones extends javax.swing.JFrame {

    /**
     * Creates new form VisualizarProveedores
     */
    ArrayList<Promocion> l;
    ControlPromocion controlp = new ControlPromocion();
    TableRowSorter<TableModel> rs;
    
    TableRowSorter<TableModel> rsProd;
    ControlProveedor controlprov = new ControlProveedor();
    ArrayList<Proveedor> lProv;
    
    boolean asignar;
    Integer codProm;

    public VisualizarPromociones() {
        initComponents();
        setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/Vista/Iconos/Publicont.png")));
        try {
            l = controlp.listar();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        tabla.setModel(modelo());
        rs = new TableRowSorter<>(tabla.getModel());
        tabla.setRowSorter(rs);

        txtBuscar.getDocument().addDocumentListener(
                new DocumentListener() {
                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        filtrar();
                    }
                });
        
        tablaProd.setModel(modeloProductos());

        rsProd = new TableRowSorter<>(tablaProd.getModel());
        tablaProd.setRowSorter(rsProd);

        txtBuscar1.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        filtrarProd();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        filtrarProd();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        filtrarProd();
                    }
                });
        
        jTabbedPane1.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                
                    if (!asignar && jTabbedPane1.getSelectedIndex() == 1) {
                        jTabbedPane1.setSelectedIndex(0);
                    } else {
                    }
                
            }
        });
        
        asignar=false;
    }

    private void filtrar() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscar.getText(), 1, 2, 3, 4, 6);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rs.setRowFilter(rf);
    }

    public DefaultTableModel modelo() {
        String[] columnas = {"Código", "Nombre",
            "Descripción", "Fecha Registro", "Fecha Inicial", "Fecha Final",
            "% Descuento"};
        DefaultTableModel tablaM = new DefaultTableModel(columnas, 0);
        try {
            l = controlp.listar();
        } catch (SQLException ex) {

        }
        for (int i = 0; i < l.size(); i++) {
            Promocion p = l.get(i);
            tablaM.addRow(new Object[]{p.getCodigo(), p.getNombre(),
                p.getDescripcion(), p.getFechaRegistro(), p.getFechaInicial(),
                p.getFechaFinal(), p.getDescuento()});
        }
        return tablaM;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        pnlProm = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        btnAgregar = new javax.swing.JButton();
        Eliminar = new javax.swing.JButton();
        btnVincular = new javax.swing.JButton();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 32767));
        jLabel1 = new javax.swing.JLabel();
        txtBuscar = new org.jdesktop.swingx.JXSearchField();
        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtBuscar1 = new org.jdesktop.swingx.JXSearchField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaProd = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Promociones");

        pnlProm.setLayout(new java.awt.BorderLayout(0, 10));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Código", "Empresa", "Teléfono", "Responsable", "Correo", "Ciudad", "Calle Principal", "Calle Secundaria", "Casa"
            }
        ));
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);

        pnlProm.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jToolBar1.setRollover(true);

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-add.png"))); // NOI18N
        btnAgregar.setFocusable(false);
        btnAgregar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAgregar);

        Eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/list-remove.png"))); // NOI18N
        Eliminar.setFocusable(false);
        Eliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Eliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EliminarActionPerformed(evt);
            }
        });
        jToolBar1.add(Eliminar);

        btnVincular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/insert-link.png"))); // NOI18N
        btnVincular.setToolTipText("Asignar promociones a productos");
        btnVincular.setFocusable(false);
        btnVincular.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnVincular.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnVincular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVincularActionPerformed(evt);
            }
        });
        jToolBar1.add(btnVincular);
        jToolBar1.add(filler1);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/edit-find.png"))); // NOI18N
        jLabel1.setText("Buscar:  ");
        jToolBar1.add(jLabel1);
        jToolBar1.add(txtBuscar);

        pnlProm.add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        jTabbedPane1.addTab("Promociones", pnlProm);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/edit-find.png"))); // NOI18N
        jLabel2.setText("Buscar:");

        jPanel4.setBackground(new java.awt.Color(255, 255, 204));
        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel3.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 153, 204));
        jLabel3.setText("Seleccione los productos a los que desea agregar la promoción.");
        jPanel4.add(jLabel3);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(132, 132, 132)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtBuscar1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, 855, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtBuscar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel2.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        tablaProd.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaProd.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jScrollPane2.setViewportView(tablaProd);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/dialog-ok-apply.png"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });
        jPanel3.add(btnAceptar);

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/dialog-cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        jPanel3.add(btnCancelar);

        jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_END);

        jTabbedPane1.addTab("Asociar Promociones a Productos", jPanel2);

        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        RegistrarPromocion ven = new RegistrarPromocion();
        ven.setVisible(true);
        ven.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                actualizar();
            }

        });
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarActionPerformed

        try {
            int i = tabla.getSelectedRow();
            DefaultTableModel model = ((DefaultTableModel) tabla.getModel());
            
            if (i >= 0) {
                i = rs.convertRowIndexToModel(i);
                int cod = Integer.parseInt(model.getValueAt(i, 0).toString());
                System.out.println("Eliminar la promoción: " + cod);
                controlp.eliminar(cod);
                actualizar();
            } else {
                JOptionPane.showMessageDialog(rootPane, "Seleccione una promoción de la tabla para eliminar");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }//GEN-LAST:event_EliminarActionPerformed

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        
    }//GEN-LAST:event_tablaMouseClicked

    private void btnVincularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVincularActionPerformed
        int i=tabla.getSelectedRow();
        if (i>=0) {
            asignar = true;
            i=rs.convertRowIndexToModel(i);
            codProm=(Integer)((DefaultTableModel)tabla.getModel()).getValueAt(i, 0);
            jTabbedPane1.setSelectedIndex(1);
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione una promoción de la tabla.");
        }
        
    }//GEN-LAST:event_btnVincularActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        int []rows=tablaProd.getSelectedRows();
        for (int i = 0; i < rows.length; i++) {
            int j=rows[i];
            if (j>=0) {
                j=rsProd.convertRowIndexToModel(j);
                String codProd=((DefaultTableModel)tablaProd.getModel()).getValueAt(j, 0).toString();
                if (codProm>=0) {
                    controlp.actualizarProd(codProd, codProm);
                    asignar=false;
                    jTabbedPane1.setSelectedIndex(0);
                }
            } else {
                JOptionPane.showMessageDialog(rootPane, "Seleccione al menos un producto de la tabla.");
            }
            
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
this.dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void actualizar() {
        tabla.setRowSorter(null);
        rs = null;
        tabla.setModel(modelo());
        rs = new TableRowSorter<>(tabla.getModel());
        tabla.setRowSorter(rs);
        filtrar();
    }

    
    /* Productos */
    
    private void filtrarProd() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscar1.getText(), 1, 2, 5);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rsProd.setRowFilter(rf);
    }

    public int prodSeleccionado() throws ArrayIndexOutOfBoundsException{

        int i = tablaProd.getSelectedRow();
        if (i>=0) {
            i = rs.convertRowIndexToModel(i);
            String cod = ((DefaultTableModel) tablaProd.getModel()).getValueAt(i, 0).toString();
            i = Integer.parseInt(cod);
        }
        return i;
    }

    public DefaultTableModel modeloProductos() {
        try {
            lProv = controlprov.listar();
        } catch (SQLException ex) {
        }
        String[] columnas = {"Código", "Nombre", "Descripción", "Precio", "Stock", "Proveedor"};
        DefaultTableModel tabla = new DefaultTableModel(columnas, 0) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false; //To change body of generated methods, choose Tools | Templates.
            }

        };
        ArrayList<Producto> lista = new ControlProdServ().listarProductos();

        for (int i = 0; i < lista.size(); i++) {
            Producto prod = lista.get(i);

            tabla.addRow(new Object[]{prod.getCodigo(), prod.getNombre(),
                prod.getDescripcion(), prod.getPrecioUnitario(),
                prod.getStock(), proveedorMostrar(prod.getCodProveedor())});
        }
        return tabla;
    }

    public String proveedorMostrar(String cod) {
        String r = "";

        for (int i = 0; i < lProv.size(); i++) {
            Proveedor proveedor = lProv.get(i);
            if (proveedor.getCodigo().equals(cod)) {
                r = cod + "-" + proveedor.getEmpresa();
                break;
            }
        }

        return r;
    }

    public void actualizarProd() {
        tablaProd.setRowSorter(null);
        rsProd = null;
        tablaProd.setModel(modeloProductos());
        rsProd = new TableRowSorter<>(tablaProd.getModel());
        tablaProd.setRowSorter(rsProd);
        filtrarProd();
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VisualizarPromociones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VisualizarPromociones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VisualizarPromociones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VisualizarPromociones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VisualizarPromociones().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Eliminar;
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnVincular;
    private javax.swing.Box.Filler filler1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPanel pnlProm;
    private javax.swing.JTable tabla;
    private javax.swing.JTable tablaProd;
    private org.jdesktop.swingx.JXSearchField txtBuscar;
    private org.jdesktop.swingx.JXSearchField txtBuscar1;
    // End of variables declaration//GEN-END:variables
}
